package net.dreamlu.controller.api;

import java.util.Date;
import java.util.Map;

import net.dreamlu.api.oauth.OauthQQ;
import net.dreamlu.config.Consts;
import net.dreamlu.model.User;
import net.dreamlu.model.WBLogin;

import org.apache.log4j.Logger;

import com.jfinal.core.Controller;

/**
 * qq登录api
 * @author L.cm
 * @date 2013-5-14 下午5:08:12
 */
public class QQLogin extends Controller {
    
    private static final Logger log = Logger.getLogger(QQLogin.class);
    
    public void index() {
        try {
            OauthQQ qq = new OauthQQ();
            redirect(qq.getAuthorizeUrl());
        } catch (Exception e) {
            log.error(e.getMessage());
            redirect("/");
        }
    }

    /**
     * 腾讯回调
     * @Title: callback
     * @param     设定文件
     * @return void    返回类型
     * @throws
     * 返回json:<url>http://wiki.connect.qq.com/get_user_info</url>
     */
    public void callback() {
        try{
            OauthQQ qq = new OauthQQ();
            Map<String, String> userInfo = qq.getUserInfoByCode(getPara("code"));
            log.error(userInfo);
            String type = "qq";
            String openid = userInfo.get("openid");
            String nickname = userInfo.get("nickname");
            String photoUrl = userInfo.get("figureurl_2");
            WBLogin login = WBLogin.dao.findByOpenID(openid, type);
            log.error("login1:\t" + login);
            if(null == login) {
                login = new WBLogin();
                login.set(WBLogin.OPENID, openid);
                login.set(WBLogin.TYPE, type);
                login.set(WBLogin.HEAD_PHOTO, photoUrl);
                login.set(WBLogin.CREATETIME, new Date());
                login.set(WBLogin.STATUS, WBLogin.STATUS_N);
                login.set(WBLogin.NICKNAME, nickname).save();
            }
            log.error("login2:\t" + login);
            // 是否邮件校验通过
            int status = login.getInt(WBLogin.STATUS);
            if (null != login.getInt(WBLogin.ID) && WBLogin.STATUS_N == status) {
                if (null == login.getInt(WBLogin.USERID)) {
                    setAttr("nouser", true);
                }
                // 跳转到绑定页
                setAttr("id", login.getInt(WBLogin.ID));
                setAttr("type", type);
                setAttr("nickname", nickname);
                setAttr("photourl", photoUrl);
                render("binding");
                return;
            }
            if (WBLogin.STATUS_Y == status) {
            	User user = User.dao.findById(login.getInt(WBLogin.USERID));
                setSessionAttr(Consts.USER_SESSION, user);
            }
        }catch(Exception e){
            log.error(e);
        }
        redirect("/admin");
    }
}
